package com.order.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.order.dto.User;
import com.order.service.UserService;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String userName = request.getParameter("userName");
		String password = request.getParameter("password");

		PrintWriter writer = response.getWriter();

		UserService userService = new UserService();

		if (userName != null && password != null) {

			try {
				User userAvilable = userService
						.validateUser(userName, password);

				if (userAvilable != null) {

					HttpSession httpSession = request.getSession(true);
					httpSession.setAttribute("user", userAvilable);

					getServletConfig().getServletContext()
							.getRequestDispatcher("/items.jsp")
							.forward(request, response);

				}

				else {

					request.setAttribute("errorMsg",
							"User IS not Avilable please try login again");

					getServletConfig().getServletContext()
							.getRequestDispatcher("/login.jsp")
							.forward(request, response);
				}

			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		writer.close();

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
